package network.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import network.netty.Common;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 *
 * </p>
 *
 * @author LovelyBigDuck
 * @date 2021/5/29 15:25
 */
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        System.out.println("收到来自客户端的数据。。。");
        ByteBuf byteBuf = msg.content();
        byte[] data = Common.getBody(msg);
        String receive = new String(data, StandardCharsets.UTF_8);
        System.out.println(receive);
        String send = "hello world";
        ByteBuf byteBufSend = Unpooled.wrappedBuffer(send.getBytes(StandardCharsets.UTF_8));
        DatagramPacket datagramPacket = new DatagramPacket(byteBufSend, msg.sender());
        ctx.writeAndFlush(datagramPacket);
        System.out.println("向客户端发送数据成功。。。");

    }
}
